<?php

namespace app\admin\controller\business;

use app\common\controller\Backend;

/**
 * 客户管理
 *
 * @icon fa fa-circle-o
 */
class Highsea extends Backend
{
    //修改是否开启关联查询属性
    protected $relationSearch = true;

    /**
     * Highsea模型对象
     * @var \app\admin\model\business\Highsea
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Business.Business');
        $this->view->assign("genderList", $this->model->getGenderList());
        $this->view->assign("dealList", $this->model->getDealList());
        $this->view->assign("authList", $this->model->getAuthList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {
            //Backend 后台基类控制器中提供的一个获取查询条件的参数方法
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $AuthWhere = ['adminid' => NULL];

            //查询出总条数 和 每页的数据量
            $total = $this->model
                ->with(['source', 'admin'])
                ->where($where)
                ->where($AuthWhere)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();  //查询总数

            $list = $this->model
                ->with(['source', 'admin'])
                ->where($where)
                ->where($AuthWhere)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();  //查询数据

            //返回的数据 下方的这两个参数名字是固定，这个是前台插件(boostrap-table这个插件的固定的)
            $result = ['total' => $total, 'rows' => $list];

            //返回json类型
            return json($result);
        }

        return $this->view->fetch();
    }

    //领取方法
    public function apply($ids = NULL)
    {
        //查询领取客户资源是否存在
        $rows = $this->model->select($ids);

        if (!$rows) {
            $this->error(__('No results were found'));
            exit;
        }

        //开启事务
        $BusinessModel = model('Business.Business');
        $ReceiveModel = model('Business.Receive');

        $BusinessModel->startTrans();
        $ReceiveModel->startTrans();

        //更新客户表
        $BusinessData = [];
        $ReceiveData = [];

        foreach ($rows as $item) {
            $BusinessData[] = [
                'id' => $item['id'],
                'adminid' => $this->auth->id,
            ];

            //组装领取记录的数据
            $ReceiveData[] = [
                'applyid' => $this->auth->id,
                'status' => 'apply', //领取
                'busid' => $item['id'], //领取客户id
            ];
        }

        //更新客户表
        $BusinessStatus = $BusinessModel->isUpdate(true)->saveAll($BusinessData);

        if ($BusinessStatus === FALSE) {
            $this->error('更新客户状态失败');
            exit;
        }

        //插入领取记录
        $ReceiveStatus = $ReceiveModel->validate('common/Business/Receive')->saveAll($ReceiveData);

        if ($ReceiveStatus === FALSE) {
            $BusinessModel->rollback();
            $this->error($ReceiveModel->getError());
            exit;
        }

        if ($BusinessStatus === FALSE || $ReceiveStatus === FALSE) {
            $ReceiveModel->rollback();
            $BusinessModel->rollback();
            $this->error('领取失败');
            exit;
        } else {
            //提交事务
            $BusinessModel->commit();
            $ReceiveModel->commit();
            $this->success('领取成功');
            exit;
        }
    }

    //分配方法
    public function allot($ids = NULL)
    {
        //查询分配客户资源是否存在
        $rows = $this->model->select($ids);

        if (!$rows) {
            $this->error(__('No results were found'));
            exit;
        }

        if ($this->request->isPost()) {
            $adminid = $this->request->param('adminid', 0, 'trim');

            //开启事务
            $BusinessModel = model('Business.Business');
            $ReceiveModel = model('Business.Receive');

            $BusinessModel->startTrans();
            $ReceiveModel->startTrans();

            //更新客户表
            $BusinessData = [];
            $ReceiveData = [];

            foreach ($rows as $item) {
                $BusinessData[] = [
                    'id' => $item['id'],
                    'adminid' => $adminid,
                ];

                //组装领取记录的数据
                $ReceiveData[] = [
                    'applyid' => $adminid,
                    'status' => 'allot', //分配
                    'busid' => $item['id'], //领取客户id
                ];
            }

            //更新客户表
            $BusinessStatus = $BusinessModel->isUpdate(true)->saveAll($BusinessData);

            if ($BusinessStatus === FALSE) {
                $this->error('更新客户状态失败');
                exit;
            }

            //插入分配记录
            $ReceiveStatus = $ReceiveModel->validate('common/Business/Receive')->saveAll($ReceiveData);

            if ($ReceiveStatus === FALSE) {
                $BusinessModel->rollback();
                $this->error($ReceiveModel->getError());
                exit;
            }


            if ($BusinessStatus === FALSE || $ReceiveStatus === FALSE) {
                $ReceiveModel->rollback();
                $BusinessModel->rollback();
                $this->error('分配失败');
                exit;
            } else {
                //提交事务
                $BusinessModel->commit();
                $ReceiveModel->commit();
                $this->success('分配成功');
                exit;
            }
        }

        //管理员
        $adminlist = build_select('adminid', model('Admin')->column('id,nickname'), [], ['class' => 'selectpicker', 'required' => '']);

        $this->assign([
            'rows' => $rows,
            'adminlist' => $adminlist
        ]);

        return $this->view->fetch();
    }
}
